package com.tuiyun.ai.face.controller;

import java.io.File;
import java.io.IOException;
import java.util.Collection;

import org.apache.commons.io.FileUtils;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.cnsugar.ai.face.FaceHelper;
import com.cnsugar.ai.face.bean.Result;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
/**
 * @Author 极品蜗牛
 * @Version 2019/6/26 18:56
 */
@Api(description = "人脸识别搜索接口")
@RestController
@RequestMapping("/faceController")
public class FaceController {

	@ApiOperation(value = "查询用户", notes = "查询用户")
	@RequestMapping(value = "/queryUserByFace", method = RequestMethod.POST)
	public ResObject queryUser(@RequestParam("img") String img) {

		// 将base64转换为byte[]
		byte[] b = Base64.decodeBase64(img);
		Result r = null;
		try {
			r = FaceHelper.search(b);

			if (r != null) {
				String picName = r.getKey();
				float similar = r.getSimilar();
				if (similar >= 0.6) {

					String userCode = picName.substring(0, picName.indexOf("."));
					return new ResObject(HttpStatus.OK.value(), 2, userCode, "");
				} else {

				}

			}

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return new ResObject(HttpStatus.OK.value(), 1, "异常报错", "");
		}

		return new ResObject(HttpStatus.OK.value(), 3, "未找到该用户", "");
	}

	@ApiOperation(value = "初始化人脸库", notes = "初始化人脸库")
	@RequestMapping(value = "/faceRegister", method = RequestMethod.POST)
	public ResObject faceRegister(@RequestParam("token") String token) {
		// String windowsPath="F:\\ai\\star";
		String linuxPath = "/usr/local/seetaface2/ai/star";
		Collection<File> files = FileUtils.listFiles(new File(linuxPath), new String[] { "jpg", "png" }, false);
		for (File file : files) {
			String key = file.getName();
			try {
				FaceHelper.register(key, FileUtils.readFileToByteArray(file));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return new ResObject(HttpStatus.OK.value(), "ok");
	}

}
